from django.db import models
from users.models import User
from django.conf import settings
import os
class File(models.Model):
    name = models.CharField(max_length=255, verbose_name='文件名')
    file = models.FileField(upload_to='uploads/', verbose_name='文件')
    uploaded_by = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='上传者')
    uploaded_at = models.DateTimeField(auto_now_add=True, verbose_name='上传时间')
    size = models.IntegerField(verbose_name='文件大小（字节）')

    def save(self, *args, **kwargs):
        if self.file and hasattr(self.file, 'size'):  # 增加存在性判断
            self.size = self.file.size
        super().save(*args, **kwargs)

    def delete(self, *args, **kwargs):
        # 删除物理文件
        if os.path.exists(self.file.path):
            os.remove(self.file.path)
        super().delete(*args, **kwargs)